package atomic;

import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

/**
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/08/21 下午 02:41
 */

public class FieldReferenceUpdateTest {


    public static void main(String[] args) {
        MyResource resource = new MyResource();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                for (int j = 0; j < 10; j++) {
                    resource.init();
                }

            }, "t" + i).start();
        }
    }


}

class MyResource {

    private volatile Boolean isInit = false;


    final static AtomicReferenceFieldUpdater<MyResource, Boolean> reference =
            AtomicReferenceFieldUpdater.newUpdater(MyResource.class, Boolean.class, "isInit");

    public void init() {
        boolean res = reference.compareAndSet(this, false, true);
        System.out.println(Thread.currentThread().getName() + ":" + (res ? "初始化成功" : "初始化失败"));
    }

}

